package com.atguigu.gulimall.product.web;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping(path = {"/", "/index.html"})
    public String indexPage(Model model) {
        // 获取一级分类属性
        List<CategoryEntity> data = categoryService.selectLevel1Categories();
        model.addAttribute("categories", data);
        return "index";
    }

    @ResponseBody
    @GetMapping(path = {"/index/catalog.json"})
    public Map<String, List<Catalog2Vo>> getCatalogJson() throws IOException, InterruptedException {
        // 获取分类属性
        Map<String, List<Catalog2Vo>> data = categoryService.getCatalogJson();
        return data;
    }

    @ResponseBody
    @GetMapping("lock")
    public R lock() throws IOException, InterruptedException {
        // 使用redisson 分布式锁
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock(); // 30s 自动续期

//        lock.lock(20, TimeUnit.SECONDS); // 无续期

        try {
            log.warn("获取分布式锁成功, 线程id: {}, 线程名称: {}", Thread.currentThread().getId(), Thread.currentThread().getName());
            Thread.sleep(15_000);
        } finally {
            log.warn("解锁分布式锁成功, 线程id: {}, 线程名称: {}", Thread.currentThread().getId(), Thread.currentThread().getName());
            lock.unlock();
        }

        return R.ok().put("data", "locked");
    }

    /**
     * 读写锁保证一定能读到最新数据；写锁：排他锁、互斥锁。读锁：共享锁。
     * 1. 写 + 读：等待写锁释放。
     * 2. 写 + 写：阻塞式执行
     * 3. 读 + 写：等待读锁释放，写锁才能执行
     * 4. 读 + 读：相当于无锁状态。
     * // todo 只要有写锁存在，就必须阻塞。
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public R write() {
        String data = UUID.randomUUID().toString();
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock wLock = readWriteLock.writeLock();
        try {
            log.info("写锁加锁之前。。{}", Thread.currentThread());
            wLock.lock();
            log.info("写锁加锁成功。。{}", Thread.currentThread());
            Thread.sleep(7000);
            stringRedisTemplate.opsForValue().set("rw-data", data);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            wLock.unlock();
            log.info("写锁解锁成功。。{}", Thread.currentThread());
        }

        return R.ok().put("data", data);
    }

    @ResponseBody
    @GetMapping("/read")
    public R read() {
        String data = "";
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        try {
            rLock.lock();
            log.info("读锁加锁成功。。{}", Thread.currentThread());
            Thread.sleep(7000);
            data = stringRedisTemplate.opsForValue().get("rw-data");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            rLock.unlock();
            log.info("读锁解锁成功。。{}", Thread.currentThread());
        }

        return R.ok().put("data", data);
    }

    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();
//        park.tryAcquire();
        return "ok";
    }

    @ResponseBody
    @GetMapping("/release")
    public String release() throws InterruptedException {
        RSemaphore release = redissonClient.getSemaphore("park");
        release.release();
        return "ok";
    }

    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch rCountDownLatch = redissonClient.getCountDownLatch("door");
        rCountDownLatch.trySetCount(3);
        rCountDownLatch.await();
        return "放学了";
    }


    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RCountDownLatch rCountDownLatch = redissonClient.getCountDownLatch("door");
        rCountDownLatch.countDown();
        return "ok";
    }
}
